package com.wingsfrog.travel.service.impl;

import com.wingsfrog.travel.modules.dao.HintDao;
import com.wingsfrog.travel.modules.dao.TeamHintDao;
import com.wingsfrog.travel.modules.dao.TeamTaskDao;
import com.wingsfrog.travel.modules.entity.Hint;
import com.wingsfrog.travel.modules.entity.TeamHint;
import com.wingsfrog.travel.service.TeamHintService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * Created by rankin on 16/4/2.
 */
@Service
public class TeamHintServiceImpl implements TeamHintService {
    @Autowired
    private TeamHintDao teamHintDao;
    @Autowired
    private HintDao hintDao;
    @Autowired
    private TeamTaskDao teamTaskDao;

    //领取线索
    @Override
    public TeamHint acceptHintByTeamTaskIdAndTaskId(Integer taskId, Integer teamTaskId) throws Exception {
        return acceptHint(taskId, teamTaskId, getNextHintLevel(teamTaskId));
    }


    //领取线索2.0
    @Override
    public TeamHint acceptHint(Integer taskId, Integer teamTaskId, Integer level) throws Exception {
        List<Hint> hints = hintDao.findByTaskId(taskId);
        if (hints.size() == 0) throw new Exception("没有线索怎么玩");

        TeamHint teamHint = getPointLevelHint(hints, level, teamTaskId);
        if (teamHint == null) throw new Exception("没有这个等级的线索");

        teamHintDao.save(teamHint);
        return teamHint;
    }

    private Integer getNextHintLevel(Integer teamTaskId) {
        TeamHint teamHint = teamHintDao.findTop1ByTeamTaskIdOrderByHintLevelDesc(teamTaskId);
        if (teamHint == null) return 1;
        return teamHint.getHintLevel() + 1;
    }


    private TeamHint getPointLevelHint(List<Hint> hints, Integer level, Integer teamTaskId) {
        TeamHint teamHint = null;
        //用代码来写，后面可能会有随机取的情况
        for (Hint hint : hints) {
            if (Objects.equals(hint.getHintLevel(), level))
                teamHint = new TeamHint(hint, teamTaskId);
        }
        return teamHint;
    }
}
